import axios from 'axios'
import EnvConfig from '../config/env.development.js'
import store from '../store/index'
import { getItem, setItem } from '../util/storage.js'

export class NetWork {
  constructor(baseURL) {
    baseURL = process.env.VUE_APP_BASE_API
    if (process.env.NODE_ENV === 'development') {
      baseURL = process.env.VUE_APP_ENV
    } else if (process.env.NODE_ENV === 'production') {
      baseURL = process.env.VUE_APP_BASE_API
    }
    // axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

    // create an axios instance
    this.service = axios.create({
      baseURL,
    })
    // 请求拦截器 request interceptor
    this.service.interceptors.request.use(function(config) {
      if (getItem('user')) {
        config.headers.Authorization = `${getItem('user')}`
      }
      config.cancelToken = new axios.CancelToken(function (cancel) {
        store.commit('pushToken', {cancelToken: cancel})
      })
      return config
    }),
      function(error) {
        return Promise.reject(error)
      }
    // 响应拦截器 response interceptor
    this.service.interceptors.response.use(
      (config) => {
        
        let res = config.data
        let headers = config.headers
        let reqConfig = config.config

        if (reqConfig.responseType === 'blob') {
          return {
            data: res,
            type: headers['content-type'],
          }
        }
        if (
          typeof res.code != 'undefined' &&
          typeof res.code != 'boolean' &&
          res.code !== 0
        ) {
          return Promise.reject(res)
        }
        return res
      },
      (error) => {
        if (axios.isCancel(error)) { // 取消请求的情况下，终端Promise调用链
          return new Promise(() => {});
        } else {
          return Promise.reject(error);
        }
      
      }
    )
  }

  post(url, parameter, config = {}) {
    return this.service.post(url, parameter, config)
  }

  get(url, parameter) {
    return this.service.get(url, {
      params: parameter,
    })
  }

  delete(url, parameter) {
    return this.service.delete(url, {
      params: parameter,
    })
  }
  download(url, parameter, config = {}) {
    return this.service.post(url, parameter, {
      ...config,
      responseType: 'blob',
    })
  }

  upload(url, parameter, config = {}) {
    return this.service.post(url, parameter, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      ...config,
    })
  }
}

export default new NetWork()
